const router = require('koa-router')();
const UserScheme = require('../db/schema/user');
const md5 = require("md5");

router.post('/register', async (ctx, next) => {
  const { username, password } = ctx.request.body
  let data = await UserScheme.findOne({ username })
  if (!data) {
    await new UserScheme({
      username,
      password: md5(password)
    }).save()
    ctx.body = {
      code: 200,
      msg: '注册成功'
    }
    ctx.session['login'] = 1
    ctx.session['username'] = username
  } else {
    if (data.username === username) {
      ctx.body = {
        code: -1,
        msg: '用户名已存在'
      }
    }
  }
})

// 登录
router.post('/login', async (ctx, next) => {
  const { username, password } = ctx.request.body
  let data = await UserScheme.findOne({ username }) //拿到用户名查询数据库
  console.log(data);

  if (!data || !data.username) {  //说明数据库没有这个名字
    ctx.body = {
      code: -1,
      msg: '用户名不存在',
    }
  } else {
    if (data.password != md5(password)) {
      ctx.body = {
        code: -1,
        msg: '密码错误',
      }
    } else {
      ctx.session['login'] = 1
      ctx.session['username'] = username
      ctx.body = {
        code: 200,
        msg: '登录成功',
      }
    }
  }
})

// 保持登录，刷新不掉
router.post('/keeplogin', async (ctx, next) => {
  if (ctx.session.username) {
    ctx.body = {
      status: ctx.session.login,
      username: ctx.session.username,
    }
  } else {
    ctx.body = {
      status: -1,
      msg: '请登录'
    }
  }
})

// 退出登录
router.post('/loginOut', async (ctx, next) => {
  if (ctx.session.username) {
    const out = ctx.session.username = ''
    const status = ctx.session.login = 0
    ctx.body = {
      status
    }
  }
})

// 保存收货地址
router.post('/address', async (ctx, next) => {
  const data = ctx.request.body
  if (ctx.session.login != 1) { // 没有登录
    ctx.body = {
      status: -1,
      msg: '请先登录'
    }
  } else {
    const username = ctx.session.username
    if (data.id) {    // 说明是更新地址
      await UserScheme.findOneAndUpdate({ username, 'addressList.id': data.id }, {
        $set: {
          'addressList.$': data
        }
      })
      ctx.body = {
        status: 200,
        msg: '更新成功'
      }
    } else {  // 新增地址
      const data2 = Object.assign(data, {
        id: String(+Date.now())
      })    // 地址id
      await UserScheme.findOneAndUpdate({ username }, {
        $push: {
          'addressList': data2
        }
      })
      ctx.body = {
        status: 200,
        msg: '添加成功'
      }
    }
  }
})

// 查询地址
router.get('/getAddress', async (ctx, next) => {
  if (ctx.session.login != 1) { // 没有登录
    ctx.body = {
      status: -1,
      msg: '请先登录'
    }
  } else {
    const res = await UserScheme.findOne({ username: ctx.session.username }).exec()
    ctx.body = {
      status: 200,
      address: res.addressList
    }
  }
})

// 删除地址
router.post('/deleteAddress', async (ctx, next) => {
  if (ctx.session.login != 1) { // 没有登录
    ctx.body = {
      status: -1,
      msg: '请先登录'
    }
  } else {
    await UserScheme.findOneAndUpdate({ username: ctx.session.username }, {
      $pull: {
        'addressList': {
          'id': ctx.request.body.id
        }
      }
    })
    ctx.body = {
      code: 200,
      msg: '删除成功'
    }
  }
})

// 查询是否已经收藏
router.post('/isCollection', async (ctx, next) => {
  const res = ctx.request.body
  const username = ctx.session.username
  if (ctx.session.login != 1) { // 没有登录
    ctx.body = {
      status: -1,
      msg: '请先登录'
    }
  } else {
    const result = await UserScheme.findOne({ username }).exec()
    let isCollection
    if (!res || !res.id) {
      isCollection = 0  // 未收藏
    } else {
      if (result.collections.length) {
        for (let i = 0; i < result.collections.length; i++) {
          if (result.collections[i].id === res.id) {
            isCollection = 1
            break
          } else {
            isCollection = 0
          }
        }
      } else {
        isCollection = 0
      }
    }
    ctx.body = {
      status: 200,
      isCollection
    }
  }
})

// 查询用户收藏列表
router.get('/collection/list', async (ctx, next) => {
  const username = ctx.session.username
  if (ctx.session.login != 1) { // 没有登录
    ctx.body = {
      status: -1,
      msg: '请先登录'
    }
  } else {
    const result = await UserScheme.findOne({ username }).exec()
    ctx.body = {
      status: 200,
      collection: result.collections || []
    }
  }

})

// 用户收藏，加入数据库
router.post('/collection', async (ctx, next) => {
  const data = ctx.request.body
  const username = ctx.session.username
  if (ctx.session.login != 1) {
    ctx.body = {
      status: -1,
      msg: '请先登录'
    }
  } else {
    await UserScheme.findOneAndUpdate({ username }, {
      $push: {
        'collections': data
      }
    })
    ctx.body = {
      status: 200,
      msg: '收藏成功'
    }
  }
})

// 取消收藏
router.post('/cancelCollection', async (ctx, next) => {
  if (ctx.session.login != 1) {
    ctx.body = {
      status: -1,
      msg: '请先登录'
    }
  } else {
    await UserScheme.findOneAndUpdate({ username: ctx.session.username }, {
      $pull: {
        'collections': {
          'id': ctx.request.body.id
        }
      }
    })
    ctx.body = {
      status: 200,
      msg: '取消收藏成功'
    }
  }
});

module.exports = router.routes();